<template>
  <div class="comment-page">
    <!-- 头部 -->
    <Navbar title="评论" placeholder bgColor="#161622">
      <template #left>
        <div class="back-btn" @click="handleBack">
          <Icon name="zuojiantou" color="#fff" size="18"></Icon>
        </div>
      </template>
    </Navbar>

    <!-- 评论列表 -->
    <div class="comment-list" ref="listContainer" @scroll="onScroll">
      <div v-for="item in commentList" :key="item.id" class="comment-item">
        <div class="avatar-container">
          <img :src="item.avatar" alt="头像" class="avatar" />
        </div>
        <div class="content">
          <div class="nickname">@{{ item.userNickname }}</div>
          <div class="comment-content">{{ item.commentContent }}</div>
          <div class="status">
            {{ item.type === 'comment' ? '评论了你的评论' : '评论了你的作品' }}
            {{ item.time }}
          </div>
        </div>
        <div class="right-content">
          <img :src="item.videoCover" alt="作品封面" class="thumbnail" @click="goToVideo(item.videoId)" />
        </div>
      </div>

      <!-- 加载中 -->
      <div v-if="loading && commentList.length > 0" class="loading">
        <Icon name="jiazailoadding" size="20" color="#f9355f" class="loading-icon" />
        <span>加载中...</span>
      </div>

      <!-- 暂无更多 -->
      <div v-if="noMore && commentList.length > 0" class="no-more">暂无更多评论</div>

      <!-- 初始无数据 -->
      <div v-if="commentList.length === 0 && !loading" class="empty">暂无评论</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import Navbar from '@/components/common/Navbar.vue'
import Icon from '@/components/common/Icon.vue'
import { formatTimeAgo } from '@/utils/time'
import { Toast } from '@/utils/showtoast'
import { useUserStore } from '@/stores/userinfo'
import { useRouter } from 'vue-router'
import { commentListAPI } from '@/api/message'

const userStore = useUserStore()
const { userId } = userStore.userInfo
const router = useRouter()

// 数据
const commentList = ref([])
const page = ref(1)
const loading = ref(false)
const noMore = ref(false)
const listContainer = ref(null)

// 获取评论列表（分页）
const loadComments = async (pageNum) => {
  if (loading.value || noMore.value) return

  loading.value = true
  try {
    const res = await commentListAPI(userId, pageNum)
    if (res.code === 200) {
      const data = res.data.map(item => ({
        ...item,
        avatar: 'http://43.138.15.137:3000' + item.userAvatar,
        videoCover: 'http://43.138.15.137:3000' + item.videoCover,
        time: formatTimeAgo(item.createdAt)
      }))

      if (data.length === 0) {
        noMore.value = true
      } else {
        commentList.value = [...commentList.value, ...data]
        page.value = pageNum + 1
      }
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    Toast('加载失败，请重试', { position: 'bottom' })
  } finally {
    loading.value = false
  }
}

// 滚动监听
const onScroll = () => {
  const el = listContainer.value
  if (!el) return

  const { scrollTop, clientHeight, scrollHeight } = el
  if (scrollHeight - scrollTop - clientHeight < 100) {
    console.log('触发加载！')
    loadComments(page.value)
  }
}

// 跳转视频
const goToVideo = (videoId) => {
  router.push(`/video/${videoId}`)
}

// 返回
const handleBack = () => router.back()

// 初始加载
onMounted(() => {
  loadComments(1)
})
</script>

<style lang="scss" scoped>
.comment-page {
  width: 100%;
  height: 100vh; // ←←← 必须是 height，不是 min-height
  display: flex;
  flex-direction: column;
  background-color: #1d1f2a;
  color: #fff;
  overflow: hidden; // 防止页面整体滚动
  padding-bottom: 46px;
}

.comment-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  -webkit-overflow-scrolling: touch;
}

.comment-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #2a2a2a;

  &:last-child {
    border-bottom: none;
  }

  .avatar-container {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 12px;

    .avatar {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .content {
    flex: 1;
    min-width: 0;

    .nickname {
      font-size: 16px;
      font-weight: 500;
      margin: 0;
    }

    .comment-content {
      font-size: 14px;
      color: #ccc;
      margin: 4px 0;
      word-break: break-word;
    }

    .status {
      font-size: 12px;
      color: #999;
    }
  }

  .right-content {
    flex-shrink: 0;
    margin-left: auto;

    .thumbnail {
      width: 60px;
      height: 60px;
      border: 1px solid #ddd;
      border-radius: 4px;
      object-fit: cover;
      cursor: pointer;
    }
  }
}

.loading,
.no-more,
.empty {
  text-align: center;
  padding: 16px;
  color: #999;
  font-size: 14px;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.loading-icon {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>